package com.cs.controller;

import com.cs.anno.Log;
import com.cs.domain.SysMenu;
import com.cs.service.SysMenuService;
import com.cs.vo.MenuAuthVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
@Api(tags = "后台菜单管理接口")
@RequestMapping("/sys/menu")
public class MenuController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询用户的权限和菜单
     * @return
     */
    @GetMapping("/nav")
    @ApiOperation(value = "查询用户菜单和权限的接口")
    @ApiResponse(code = 200,message = "成功",response = MenuAuthVo.class)
    @Log(value = "查询用户的权限和菜单")
    public ResponseEntity<MenuAuthVo> findMenuAuth(){
        //获得当前登录的用户id
        String userId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //查询用户的菜单
        List<SysMenu> menus=sysMenuService.findMenus(userId);
        //用户的权限 不需要查询登录时已经保存了
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        List<String> auths = new ArrayList<>();
        if(!CollectionUtils.isEmpty(authorities)){
            authorities.forEach(auth->{
                auths.add(auth.getAuthority());
            });
        }
        MenuAuthVo menuAuthVo = new MenuAuthVo();
        //设置用户的权限
        menuAuthVo.setAuthorities(auths);
        //设置用户的菜单
        menuAuthVo.setMenuList(menus);
        return ResponseEntity.ok(menuAuthVo);
    }

}
